<?php

namespace backend\modules\business\controllers;

use backend\controllers\AdminController;
use backend\modules\business\models\BusinessPig;
use common\components\Helper;
use common\components\IDValidator\IDValidator;
use common\components\Upload;
use Yii;
use common\models\business\BusinessPerson;
use backend\modules\business\models\BusinessPersonSearch;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * PersonController implements the CRUD actions for BusinessPerson model.
 */
class PersonController extends AdminController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all BusinessPerson models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new BusinessPersonSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }




    /**
     * Displays a single BusinessPerson model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new BusinessPerson model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new BusinessPerson();

        if(Yii::$app->request->isPost){
            $model->createtime = time();
            $model->setAttribute('identity_img',Upload::upload($model,'identity_img'));
        }
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $postdata = Yii::$app->request->post();
            if(!empty($postdata['BusinessPerson']['pigs'])){
                foreach ($postdata['BusinessPerson']['pigs'] as $key => $row){
                    Yii::$app->db->createCommand()->update(BusinessPig::tableName(),['headpersonid'=>$model->id,'headperson'=>$model->name],'id=:id',[':id'=>$row])
                        ->execute();
                }
            }
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing BusinessPerson model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) {
            $model->setScenario('update');
            if (false !== $photo = Upload::upload($model, 'identity_img')) {
                $model->setAttribute('identity_img', $photo);
            }
            $postdata = Yii::$app->request->post();
            if(!IDValidator::getInstance()->isValid($model->identityno)){
                return $this->dialog('身份证格式错误');
            }

            if ($model->save()) {
                $pids = (new Query())->select('id,no')->from(BusinessPig::tableName())
                    ->where('headpersonid=:id',[':id'=>$model->id])
                    ->all();
                if(!empty($pids)){
                    $pids = ArrayHelper::getColumn($pids,'id');
                }else{
                    $pids = [];
                }
                if(!empty($postdata['BusinessPerson']['pigs'])){

                    $diff = array_diff($pids,$postdata['BusinessPerson']['pigs']);
                    foreach ($postdata['BusinessPerson']['pigs'] as $key => $row){
                        Yii::$app->db->createCommand()->update(BusinessPig::tableName(),['headpersonid'=>$model->id,'headperson'=>$model->name],'id=:id',[':id'=>$row])
                            ->execute();
                    }
                }else{
                    $diff = $pids;
                }


                //去掉删除的
                foreach ($diff as $key => $row){
                    Yii::$app->db->createCommand()->update(BusinessPig::tableName(),['headpersonid'=>0,'headperson'=>''],'id=:id',[':id'=>$row])
                        ->execute();
                }
                return $this->redirect(['view', 'id' => $model->id]);
            }
        }else {
            $pids = (new Query())->select('id,no')->from(BusinessPig::tableName())
                ->where('headpersonid=:id',[':id'=>$model->id])
                ->all();
            $ids = [];
            foreach ($pids as $key => $row){
                $ids[$row['id']] = '['.$row['id'].']'.$row['no'].']';
            }

            return $this->render('update', [
                'model' => $model,
                'ids' => $ids,
            ]);
        }
    }

    /**
     * Deletes an existing BusinessPerson model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the BusinessPerson model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return BusinessPerson the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = BusinessPerson::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
